<?php
declare(strict_types=1);
namespace Hangpu888\Hpadmin\controller;

use Exception;
use Hangpu888\Hpadmin\Controller;
use Hangpu888\Hpadmin\model\Admin as ModelAdmin;
use Hangpu888\Hpadmin\model\AdminLog;
use Hangpu888\Hpadmin\utils\Json;
use Hangpu888\Hpadmin\utils\manager\TokenManager;
use Hangpu888\Hpadmin\validate\Admin;

class Publics extends Controller
{
    /**
     * 应用信息
     *
     * @return void
     */
    public function site()
    {
        try {
            $moduleName = $this->getModuleName();
            if (!$moduleName) {
                throw new Exception('应用名称错误');
            }
            $_config = config('plugin.hangpu888.hpadmin.app.background');
            if (!isset($_config[$moduleName])) {
                throw new Exception('应用名称不存在');
            }
            $data                           = getHpConfig();
            $data['_config']                = $_config[$moduleName];
            return Json::successRes($data);
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage());
        }
    }

    /**
     * 系统登录
     *
     * @return void
     */
    public function login()
    {
        try {
            // 获取数据
            $data = request()->post();
            // 数据验证
            hpValidate(new Admin,$data,'login');

            // 查询数据
            $map['username'] = $data['username'];
            $user = ModelAdmin::where($map)->find();
            if (!$user) {
                throw new Exception('登录账号错误');
            }
            // 实例日志类
            $logModel = new AdminLog;
            // 获取请求路径
            $path = substr(request()->path(),1);
            // 获取登录者IP地址
            $ip = request()->getRealIp($safe_mode=true);
            $data['password'] = md5($data['password']);
            $data['remarks'] = '登录成功';
            if ($user->password != $data['password']) {
                $remarks = '登录密码错误';
                $data['remarks'] = $remarks;
                $logModel->addLog($path,$ip,$user->id,$user->role_id,0,$data);
                throw new Exception($remarks);
            }
            if ($user->status == 0) {
                $remarks = '该账号已被锁定';
                $data['remarks'] = $remarks;
                $logModel->addLog($path,$ip,$user->id,$user->role_id,0,$data);
                throw new Exception($remarks);
            }
            // 生成令牌
            $token = TokenManager::_create_token((string)$user->id,'admin','','\\Hangpu888\\Hpadmin\\model\\Admin');
            // 登录完成
            $logModel->addLog((string)$path,(string)$ip,(int)$user->id,(int)$user->role_id,0,$data);

            // 更新登录信息
            $user->last_login_ip = $ip;
            $user->last_login_time = date('Y-m-d H:i:s');
            $user->save();

            // 返回数据
            return Json::successFul('登录成功',['token'=> $token]);
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage());
        }
    }
}